<?php
// 连接数据库

@include_once('connect.php');


//排序分页  根据关键字搜索(可为空)进行升(降)序

$res = [];

$sort = $_GET['sort'];
$sortType = $_GET['sortType'] ;


// 每页显示几条数据
$size = $_GET['size'];
// 第几页的数据
$page = $_GET['page'];

// 搜索的关键字  --- 此参数可以没有
$kw = $_GET['kw'];
$res = [];

if ($size && $page) {


    //根据goods_title的关键字$kw按照$sort排序 查询数据的总数量
    $sql = "SELECT count(*) pageLen from goods_list where goods_title like '%$kw%' order by $sortType $sort";
    $data = mysqli_query($conn, $sql);
    $data = mysqli_fetch_array($data);

    // 拿到数据的长度
    $pageLen = $data['pageLen'];


    $start = $size * ($page - 1); //表示页数

    //限制每一页显示$size个数据
    $sql = "select * from goods_list where goods_title like '%$kw%' order by $sortType $sort limit $start,$size  ";
    // 运行
    $data = mysqli_query($conn, $sql);
    // 得到的是一个结果集   转数组



    $list = [];
    while ($aa = mysqli_fetch_array($data)) {
        // 第一个参数是数组，第二个参数是值
        $arr = [];
        // 把需要的数据重新存入arr这个数组中
        $arr['goods_img'] = $aa['goods_img'];
        $arr['goods_price'] = $aa['goods_price'];
        $arr['goods_des'] = $aa['goods_des'];
        $arr['goods_title'] = $aa['goods_title'];
        $arr['goods_id'] = $aa['goods_id'];
        $arr['goods_name'] = $aa['goods_name'];
        $arr['goods_type'] = $aa['goods_type'];
        array_push($list, $arr);
    }

    if ($list) {
        $res['status'] = true;
        $res['msg'] = '数据请求成功';
        $res['list'] = $list;
        // 后端需要把总数据的长度返回给前端
        $res['pageLen'] = $pageLen;
    } else {
        $res['status'] = false;
        $res['msg'] = '数据库错误';
    }
} else {
    $res['status'] = false;
    $res['msg'] = '前端数据有误';
}


echo (json_encode($res));
